package com.byf.product.vo;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.IOException;

public class Test {

    /**
     * 下载文件并保存到本地
     *
     * @param fileUrl  文件的URL
     * @param savePath 本地保存路径
     */
    public static void downloadFile(String fileUrl, String savePath) {
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(5000); // 连接超时时间
            httpURLConnection.setReadTimeout(5000); // 读取超时时间

            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (InputStream inputStream = httpURLConnection.getInputStream();
                     FileOutputStream fos = new FileOutputStream(savePath)) {

                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        fos.write(buffer, 0, bytesRead);
                    }

                    System.out.println("文件已成功下载并保存到: " + savePath);
                }
            } else {
                System.err.println("无法下载文件，HTTP响应码: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("下载文件时发生错误: " + e.getMessage());
        }
    }

    /**
     * 从URL中提取文件名
     * @param url 完整的URL
     * @return 文件名
     */
    public static String extractFileNameFromUrl(String url) {
        // 找到最后一个斜杠的位置
        int lastSlashIndex = url.lastIndexOf('/');
        if (lastSlashIndex != -1 && lastSlashIndex < url.length() - 1) {
            // 提取斜杠之后的部分
            return url.substring(lastSlashIndex + 1);
        }
        return null; // 如果没有找到斜杠或斜杠是最后一个字符，则返回null
    }



    public static void main(String[] args) {
        String fileUrl = "https://cdn.discordapp.com/attachments/1285976574868455455/1319190483775520860/barbara_xi5513594_68884_A_cartoon-style_image_of_a_30-year-old__efebe121-074a-472f-b2ea-69cb2f6be42d.png?ex=67650f60&is=6763bde0&hm=71c8cb17da9b0369a5f3e358c974e1158cca3bb5f5ba8a798ea329f80b682058&";
        String savePath = "D:\\QMDownload\\" + extractFileNameFromUrl(fileUrl);
        downloadFile(fileUrl, savePath);
    }


}
